package com.myr.config;

import com.myr.service.Userservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.net.PasswordAuthentication;

/**
 * @author myr
 * @version 1.0
 * @date 2023/1/3 12:10
 */
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    //指定账户和密码来源

    @Autowired
    private Userservice userservice;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userservice).passwordEncoder(passwordEncoder());
    }

    //设置security认证的规则

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                //这个路径必须跟登录的提交路径一致
                .loginProcessingUrl("/login")
                //设置自定义登录界面
                .loginPage("/login.html")
                //登录成功后的转发界面
                .successForwardUrl("/main")
                .permitAll();

        //没有权限时候跳转的界面
        http.exceptionHandling().accessDeniedPage("/403.html");

        //禁用跨站伪造请求，不使用csrf过滤器
        http.csrf().disable();

        //设置其他路径必须登录才能访问
        http.authorizeRequests().anyRequest().authenticated();
    }
}
